package com.gdpu.pbss.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.gdpu.pbss.pojo.Manager;
import com.gdpu.pbss.pojo.User;
import com.gdpu.pbss.service.ManagerService;
import com.gdpu.pbss.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static ManagerService staticmanagerService;

    private static UserService staticuserService;

    @Resource
    private ManagerService managerService;

    @Resource
    private UserService userService;


    @PostConstruct
    public void  setManagerService(){
        staticmanagerService=managerService;
    }

    @PostConstruct
    public void  setUserService(){staticuserService=userService;}

    public static String getManagerToken(Integer manageId,String managePassword) {
            return  JWT.create().withAudience(String.valueOf(manageId))
                    .withExpiresAt(DateUtil.offsetHour(new Date(), 2))//两小时后token过期。
                     .sign(Algorithm.HMAC256(managePassword));//将manage_id放到token中




    }

    public static String getUserToken(Integer userId,String passward){
        return  JWT.create().withAudience(String.valueOf(userId))
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2))//两小时后token过期。
                .sign(Algorithm.HMAC256(passward));//将manage_id放到token中
    }

    public static Manager getManager(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)){
                String manageId = JWT.decode(token).getAudience().get(0);
                return staticmanagerService.getById(manageId);
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }


    public static User getUser(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("utoken");
            if (StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticuserService.getById(userId);
            }
        }catch (Exception e){
            return null;
        }
        return null;
    }
}
